<template>
  <div id="userManagePage">
<!--    搜索功能-->
    <div class="searchModel">
      <a-form layout="inline" :model="searchParams" @finish="doSearch">
        <a-form-item>
          <a-input v-model:value="searchParams.userAccount" placeholder="输入账号搜索" allow-clear/>
        </a-form-item>
        <a-form-item>
          <a-input v-model:value="searchParams.userName" placeholder="输入用户名搜索" allow-clear/>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit">搜索</a-button>
        </a-form-item>
      </a-form>
    </div>
<!--    用户管理模块-->
    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="pagination"
      @change="doTableChange"
    >
      <template #headerCell="{ column }"></template>

      <template #bodyCell="{ column, record }">
        <template v-if="['userName', 'userAvatar', 'userProfile', 'userRole'].includes(column.dataIndex)">
            <a-input
              v-if="editableData[record.id]"
              v-model:value="editableData[record.id][column.dataIndex]"
            />
        </template>
        <template v-if="column.dataIndex === 'userAvatar'">
          <a-image :src="record.userAvatar" :width="100" />
        </template>
        <template v-if="column.dataIndex === 'userRole'">
          <div v-if="record.userRole === 'admin'">
            <a-tag color="green">管理员</a-tag>
          </div>
          <div v-else>
            <a-tag color="blue">普通用户</a-tag>
          </div>
        </template>
        <template v-else-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-else-if="column.key === 'action'">
          <div class="editRow" style="margin-bottom: 2px">
            <span v-if="editableData[record.id]">
              <a-typography-link @click="saveEdit(record.id)">保存</a-typography-link>
              <a-popconfirm title="确定取消?" @confirm="cancelEdit(record.id)">
                <a>取消</a>
              </a-popconfirm>
            </span>
            <span v-else>
              <a-button @click="doEdit(record.id)">编辑</a-button>
            </span>
          </div>
          <a-button danger @click="doDelete(record.id)">删除</a-button>
        </template>
      </template>
    </a-table>
  </div>
</template>
<script lang="ts" setup>
import {computed, onMounted, reactive, ref, UnwrapRef} from 'vue'
import {
  deleteUserUsingPost,
  getUserByIdUsingGet,
  listUserVoByPageUsingPost,
  updateUserUsingPost
} from '@/api/userController'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn';
import {cloneDeep} from "lodash";
dayjs.locale('zh-cn');

// 搜索用户数据
const doSearch = () => {
  // 每次搜索从第一页开始搜，否则可能搜不到
  searchParams.current = 1
  fetchData()
}

//点击删除按钮删除记录操作
const doDelete = async (id: string) => {
  if(!id) return;
  // 调用后端方法，根据id删除记录
  const res = await deleteUserUsingPost({ id });
  if(res.data.code === 0) {
    message.success('删除成功');
    // 再次获取数据刷新
    fetchData()
  }else {
    message.error('删除失败，' + res.data.message)
  }
}

const editableData: UnwrapRef<Record<string, API.UserUpdateRequest>> = reactive({});

// 点击button开始编辑用户
const doEdit = async (id: bigint) => {
  if(!id) return;
  try {
    // 调用后端方法获取用户id对应的信息
    const res = await getUserByIdUsingGet({ id });
    if(res.data.code === 0) {
      editableData[id] = cloneDeep(res.data.data);
    } else {
      message.error('获取用户数据失败' + res.data.message)
    }
  }catch (error) {
    message.error('请求错误' + error)
  }
}

// 保存编辑后的用户信息
const saveEdit = async (id: bigint) => {
  if (!id || !editableData[id]) return;
  try {
    // 创建一个update请求参数相同的对象，根据id获取前端用户输入的内容
    const updateData: API.UserUpdateRequest = {
      id: editableData[id].id,
      userName: editableData[id].userName,
      userAvatar: editableData[id].userAvatar,
      userProfile: editableData[id].userProfile,
      userRole: editableData[id].userRole,
    };
    // 调用后端 API 更新用户数据
    const res = await updateUserUsingPost(updateData);
    if (res.data.code === 0) {
      // 更新前端数据源，并展示
      const index = dataList.value.findIndex(item => item.id === id);
      if (index !== -1) {
        dataList.value[index] = { ...editableData[id] };
      }
      // 删除编辑状态
      delete editableData[id];
      message.success('保存成功');
    } else {
      message.error('保存失败: ' + res.data.message);
    }
  } catch (error) {
    message.error('请求错误: ' + error);
  }
}

// 取消编辑
const cancelEdit = async (id: bigint) => {
  if (!id || !editableData[id]) return;

  delete editableData[id];
}

// 表格列标题定义
const columns = [
  {
    title: 'id',
    dataIndex: 'id',
  },
  {
    title: '账号',
    dataIndex: 'userAccount',
  },
  {
    title: '用户名',
    dataIndex: 'userName',
  },
  {
    title: '头像',
    dataIndex: 'userAvatar',
  },
  {
    title: '简介',
    dataIndex: 'userProfile',
  },
  {
    title: '用户角色',
    dataIndex: 'userRole',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    title: '操作',
    key: 'action',
  },
]


const dataList = ref<API.UserVO[]>([]) //记录用户数组
const total = ref(0)  // 总用户条数

const searchParams = reactive<API.UserQueryRequest>({
  current: 1,
  pageSize: 10,
})

// 获取后端用户数据
const fetchData = async () => {
  const res = await listUserVoByPageUsingPost({
    ...searchParams,
  })
  if (res.data.data) {
    dataList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
}

// 让页面第一次刷新时获取一次，之后不必重复获取
onMounted(() => {
  fetchData()
})

//分页参数
const pagination = computed(() => {
  return {
    current: searchParams.current ?? 1,
    pageSize: searchParams.pageSize ?? 10,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total) => `共${total}条`,
  }
})

// 表格变化处理
const doTableChange = (page: any) => {
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}
</script>
<style scoped>
#userManagePage {

}
.searchModel {
  padding-bottom: 5px;
}

</style>
